package com.xhwl.logistics.controller.cent;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.logistics.service.cent.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


@RestController
@Slf4j
@Api(tags = "文件相关接口")
@RequestMapping(value = "file")
public class FileController {

    @Autowired
    IFileService fileService;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "unit", value = "文件单位    1、字节（byte） 2、kb(千字节)  3、MB",required = true, defaultValue = "1"),
    })
    @PostMapping(value = "/upload2")
    @ApiOperation(value = "文件上传2")
    public ResultJson uploadFile2(@RequestParam(value = "file") MultipartFile file
            , @RequestParam(name = "unit",required = false) Integer unit) {
        log.info("uploadFile() called with parameters => 【files = {}】", file);
        List<String> urls = new ArrayList<>();
        String url = null;
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //文件大小
            long size = Optional.ofNullable(file).map(x -> x.getSize()).orElse(null);
            //获取文件名称
            String originalFilename = Optional.ofNullable(file).map(x -> x.getOriginalFilename()).orElse(null);
            //获取文件返回地址
            url = Optional.ofNullable(fileService.uploadeFile(file)).orElse(null);
            url = (String) Optional.ofNullable(JSONObject.parseObject(url, Map.class)).map(x -> x.get("result")).orElse(null);
            if (ObjectUtil.isNotNull(url)) {
                resultMap.put("size", size);
                resultMap.put("unit", "byte");
                if ("2".equals(unit.toString())) {
                    resultMap.put("size", size / 1024);
                    resultMap.put("unit", "kb");
                }
                if ("3".equals(unit.toString())) {
                    resultMap.put("size", (size / 1024 / 1024));
                    resultMap.put("unit", "mb");
                }
                resultMap.put("url", url);
                resultMap.put("fileName", originalFilename);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultJson.success(resultMap);
    }
}
